package com.liziba.unsafe.clone;

import sun.misc.Unsafe;

/**
 * <p>
 *      计算大小工具类
 *      原文链接：https://blog.csdn.net/zhxdick/article/details/52003123
 * </p>
 *
 * @Author: Liziba
 * @Date: 2021/5/24 23:10
 */
public class CalculateInfoSizeUtil {


    private static Object helperArray[] = new Object[1];
    /**
     * 获取对象起始位置偏移量
     * @param unsafe
     * @param object
     * @return
     */
    public static long getObjectAddress(Unsafe unsafe, Object object){
        helperArray[0] = object;
        long baseOffset = unsafe.arrayBaseOffset(Object[].class);
        return unsafe.getLong(helperArray, baseOffset);
    }

    private final static ClassIntrospector ci = new ClassIntrospector();

    /**
     * 获取Object的大小
     * @param object
     * @return
     */
    public static long getObjectSize(Object object){
        ObjectInfo res = null;
        try {
            res = ci.introspect(object);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return res.getDeepSize();
    }


}
